package com.wyg.demo.service.impl;

import cn.hutool.log.Log;
import cn.hutool.log.dialect.log4j2.Log4j2Log;
import com.wyg.demo.service.CompletableFutureService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author WenYanguang
 * @since 2023/3/21
 */
@Service
public class CompletableFutureServiceImpl implements CompletableFutureService {
    private static final Log LOG = new Log4j2Log(CompletableFutureServiceImpl.class);
    @Resource
    private final ThreadPoolExecutor threadPoolExecutor;

    public CompletableFutureServiceImpl(ThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    @Override
    public void execute(List<String> threadList) {
        try {
            for (int i = 0; i < 1000; i++) {
                CompletableFuture<List<String>> future = CompletableFuture.supplyAsync(() -> {
                    threadList.add(Thread.currentThread().getName());
                    return threadList;
                }, threadPoolExecutor).whenComplete((l, e) -> {
                    if (threadList.size() > 100 && e == null) {
                        LOG.info("本次线程任务执行完成" + Thread.currentThread().getName());
                    }
                }).exceptionally(e -> {
                    throw new RuntimeException(e.getMessage());
                });
            }
        } finally {
            threadPoolExecutor.shutdown();
            LOG.info("线程池已关闭");
        }
    }
}
